package cn.itlaobing.web.servlet;

import com.google.zxing.BarcodeFormat;
import com.google.zxing.EncodeHintType;
import com.google.zxing.MultiFormatWriter;
import com.google.zxing.WriterException;
import com.google.zxing.client.j2se.MatrixToImageWriter;
import com.google.zxing.common.BitMatrix;
import org.apache.commons.codec.binary.Base64;
import org.apache.commons.lang3.RandomStringUtils;

import javax.imageio.ImageIO;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.awt.image.BufferedImage;
import java.io.BufferedInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

/**
 * Created by Administrator on 2017/11/22 0022.
 */

@WebServlet("/payment")
public class PaymentServlet extends HttpServlet {

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String qrText="https://www.baidu.com?n="+ RandomStringUtils.random(10,true,true);

        int width = 400; // 图像宽度
        int height = 400; // 图像高度
        String format = "png";// 图像类型
        Map<EncodeHintType, Object> hints = new HashMap<EncodeHintType, Object>();
        hints.put(EncodeHintType.CHARACTER_SET, "UTF-8");
        BitMatrix bitMatrix = null;// 生成矩阵
        try {
            bitMatrix = new MultiFormatWriter().encode(qrText,
                    BarcodeFormat.QR_CODE, width, height, hints);

            // String qrBase64String=MatrixToImageWriter.writeToBase64(bitMatrix,"png","f:/aaa.png");
           BufferedImage bufferedImage= MatrixToImageWriter.toBufferedImage(bitMatrix);

            ByteArrayOutputStream bos=new ByteArrayOutputStream();
            ImageIO.write(bufferedImage,format,bos);
            byte[] qrByte=bos.toByteArray();
            bos.close();
            String qrBase64String= Base64.encodeBase64String(qrByte);

            resp.setContentType("application/text;charset=UTF-8");
            resp.getWriter().write("data:image/png;base64,"+qrBase64String);
            resp.getWriter().close();
        } catch (WriterException e) {
            e.printStackTrace();
        }


    }
}
